package com.uduemc.biso.node.module.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.entities.HWatermark;
import com.uduemc.biso.node.module.service.HWatermarkService;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping("/h-watermark")
@Slf4j
public class HWatermarkController {

	@Autowired
	HWatermarkService hWatermarkServiceImpl;

	/**
	 * 通过 hostId 获取到 HWatermark 数据，如果通过过滤的条件获取的数据库为空会创建一条数据返回
	 * 
	 * @param hostId
	 * @return
	 */
	@GetMapping("/find-if-not-exist-by-host-id/{hostId:\\d+}")
	public RestResult findIfNotExistByHostId(@PathVariable("hostId") Long hostId) {
		HWatermark data = hWatermarkServiceImpl.findIfNotExistByHostId(hostId);
		if (data == null) {
			return RestResult.noData();
		}
		return RestResult.ok(data, HWatermark.class.toString());
	}

	/**
	 * 更新 hWatermark 数据
	 * 
	 * @param hWatermark
	 * @param errors
	 * @return
	 */
	@PostMapping("/update-by-id")
	public RestResult updateById(@Valid @RequestBody HWatermark hWatermark, BindingResult errors) {
		log.info("updateById: " + hWatermark.toString());
		if (errors.hasErrors()) {
			Map<String, Object> message = new HashMap<>();
			for (FieldError fieldError : errors.getFieldErrors()) {
				String field = fieldError.getField();
				String defaultMessage = fieldError.getDefaultMessage();
				message.put(field, defaultMessage);
			}

			return RestResult.error(message);
		}
		HWatermark findOne = hWatermarkServiceImpl.findOne(hWatermark.getId());
		if (findOne == null) {
			return RestResult.noData();
		}
		HWatermark data = hWatermarkServiceImpl.updateById(hWatermark);
		return RestResult.ok(data, HWatermark.class.toString());
	}

}
